<template>
  <BasicDrawer
    class="wyf-drawer"
    v-bind="$attrs"
    @register="registerBaseDrawer"
    :loading="loading"
    title="房源详情"
    width="60%"
    :showFooter="showFooter"
    destroyOnClose
  >
    <div>
      <template v-for="item in detailSchema">
        <div class="wyf-form-item-box" :key="item.field" v-if="!item?.ifShow || item.ifShow({ values: info })">
          <template v-if="item.slot">
            <template v-if="item.type == 'card'">
              <a-card style="width: 100%" :tab-list="tabList" :active-tab-key="key" @tab-change="(key) => onTabChange(key, 'key')">
                <!-- 抓拍记录时间筛选 -->
                <div v-if="key === '2'" style="margin-bottom: 16px; display: flex; align-items: center; gap: 12px">
                  <span>时间范围：</span>
                  <a-range-picker
                    v-model:value="timeRange"
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['开始时间', '结束时间']"
                    @change="onTimeRangeChange"
                    style="width: 350px"
                  />
                  <a-button type="primary" @click="handleSearch">查询</a-button>
                  <a-button @click="handleReset">重置</a-button>
                </div>
                <BasicTable @register="registerTable">
                  <template #action="{ record }">
                    <TableAction :actions="getTableAction(record)" />
                  </template>
                  <template #zpzpids="{ text }">
                    <div v-if="text" style="display: flex; gap: 4px; flex-wrap: wrap;">
                      <a-image-preview-group>
                        <template v-for="(url, index) in getImageUrls(text)" :key="index">
                          <a-image
                            :width="60"
                            :height="60"
                            :src="url"
                            style="object-fit: cover; border: 1px solid #d9d9d9; border-radius: 4px; cursor: pointer;"
                          />
                        </template>
                      </a-image-preview-group>
                    </div>
                    <span v-else>-</span>
                  </template>
                </BasicTable>
              </a-card>
            </template>
            <div v-else class="wyf-form-item-title">{{ item.field }} <span v-if="item.field == '入住记录'"></span></div>
          </template>
          <template v-else>
            <div class="wyf-form-item-label">{{ item.label }}：</div>
            <div class="wyf-form-item-text" v-if="item.component == 'JImageUpload'">
              <a-image-preview-group v-if="info[item.field] && info[item.field].length > 0">
                <template v-for="(img, index) in info[item.field]" :key="`${item.field}${index}`">
                  <a-image :width="100" :height="100" :src="img" />
                  <span class="wyf-m-r-20"></span>
                </template>
              </a-image-preview-group>
              <template v-else>
                <a-image
                  :width="100"
                  :height="100"
                  src="https://www.antdv.com/#error"
                  fallback=""
                />
              </template>
            </div>

            <!-- ApiTreeSelect -->
            <div class="wyf-form-item-text" v-else-if="item.component == 'ApiTreeSelect'">
              {{ info[`${item.field}Full_dictText`] || '' }}
            </div>
            <div class="wyf-form-item-text" v-else>
              <template v-if="item.render">
                <span :class="item?.color && item?.color(info[item.field])">{{ item.render(info[item.field]) }} </span></template
              >
              <template v-else> {{ info[item.field] || '' }} </template>
            </div>
          </template>
        </div>
      </template>
    </div>
  </BasicDrawer>
  <!--入住详情抽屉-->
  <OrderDetailDrawer @register="registerDrawer" />
</template>
<script lang="ts" setup>
  import { ref, useAttrs } from 'vue';
  import type { Dayjs } from 'dayjs';
  import { detailSchema, historyColumns, captureColumns } from '../approved.data';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { detail, wyfOrders, captureRecords } from '../approved.api';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import OrderDetailDrawer from '/@/views/checkin/checkinRecord/components/DetailDrawer.vue';

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const rowId = ref('');
  const showFooter = ref(true);
  const info = ref({});
  const loading = ref(false); //审核 pending

  const key = ref('1');
  const noTitleKey = ref('app');
  const timeRange = ref<any[]>([]);
  const tabList = [
    {
      key: '1',
      tab: '入住记录',
    },
    {
      key: '2',
      tab: '抓拍记录',
    },
  ];

  //注册drawer
  const [registerDrawer, { openDrawer }] = useDrawer();
  //注册drawer
  const [registerBaseDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
    // 重置到入住记录tab
    key.value = '1';
    timeRange.value = [];
    setProps({ searchInfo: { houseId: data.record.id } });
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: true, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    rowId.value = data.record.id;
    loading.value = true;
    let res = await detail({ id: rowId.value });
    //附件赋值
    let fjlx_2 = [] as String[],
      fjlx_4 = [] as String[],
      fjlx_6 = [] as String[],
      fjlx_5 = [] as String[];

    const cqrFjids: { fjlx: string; fileurl: string; id: string }[] = res.pics || [];
    if (cqrFjids && cqrFjids.length > 0) {
      for (let i = 0; i < cqrFjids.length; i++) {
        if (cqrFjids[i].fjlx == '2') {
          fjlx_2.push(cqrFjids[i].fileurl);
        } else if (cqrFjids[i].fjlx == '4') {
          fjlx_4.push(cqrFjids[i].fileurl);
        } else if (cqrFjids[i].fjlx == '5') {
          fjlx_5.push(cqrFjids[i].fileurl);
        } else if (cqrFjids[i].fjlx == '6') {
          fjlx_6.push(cqrFjids[i].fileurl);
        }
      }
    }
    res.jyrlx = res.hoperator.jyrlx;
    res.jyrzjhm = res.hoperator.jyrzjhm;
    res.jyrlxdh = res.hoperator.jyrlxdh;
    res.jyrxm = res.hoperator.jyrxm;
    data.record.jyrdwmc = res.hoperator.jyrdwmc;
    data.record.tyshxydm = res.hoperator.tyshxydm;

    res.cqrlx = res.hpownerList && res.hpownerList[0]?.cqrlx;
    res.cqrdwmc = res.hpownerList && res.hpownerList[0]?.cqrdwmc;
    res.cqrtyshxydm = res.hpownerList && res.hpownerList[0]?.tyshxydm;
    res.cqrxm = res.hpownerList && res.hpownerList[0]?.cqrxm;
    res.cqrzjhm = res.hpownerList && res.hpownerList[0]?.cqrzjhm;
    res.cqrlxdh = res.hpownerList && res.hpownerList[0]?.cqrlxdh;

    res.shbz = (res.review && res.review.shbz) || '';
    res.shyj = (res.review && res.review.shyj) || '';
    res.shrxm = (res.review && res.review.shrxm) || '';
    res.createTime = (res.review && res.review.createTime) || '';

    res = { ...data.record, ...res, fjlx_2, fjlx_4, fjlx_5, fjlx_6 };

    info.value = res;
    setDrawerProps({ confirmLoading: false });
    loading.value = false;
  });
  //注册table
  const [registerTable, { reload, updateTableDataRecord, setProps, setColumns }] = useTable({
    title: '',
    api: wyfOrders,
    columns: historyColumns,
    // formConfig: {
    //   //update-begin---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示
    //   labelWidth: 60,
    //   //update-end---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示
    //   schemas: searchUserFormSchema,
    //   autoSubmitOnEnter: true,
    // },
    striped: false,
    useSearchForm: false,
    showTableSetting: false,
    clickToRowSelect: false,
    bordered: false,
    showIndexColumn: false,
    // 【issues/1064】列设置的 cacheKey
    //tableSetting: { fullScreen: true, cacheKey: 'role_user_table' },
    canResize: false,
    rowKey: 'id',
    actionColumn: {
      width: 60,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
      align: 'left',
    },
    scroll: { x: 600 },
  });
  /**
   * 操作栏
   */
  function onTabChange(value: string, type: string) {
    key.value = value;
    timeRange.value = [];
    if (value == '1') {
      // 入住记录 - 使用 historyColumns 和 wyfOrders API，显示操作列
      setColumns(historyColumns);
      setProps({
        api: wyfOrders,
        searchInfo: { houseId: rowId.value },
        actionColumn: {
          width: 60,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
          align: 'left',
        },
      });
    } else if (value == '2') {
      // 抓拍记录 - 使用 captureColumns 和 captureRecords API，隐藏操作列
      setColumns(captureColumns);
      setProps({
        api: captureRecords,
        searchInfo: { houseId: rowId.value },
        actionColumn: undefined,
      });
    }
    // 重新加载数据
    reload();
  }
  function getTableAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
    ];
  }
  /**
   * 详情
   */
  async function handleDetail(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }

  /**
   * 时间范围变化
   */
  function onTimeRangeChange(dates: any, dateStrings: any) {
    console.log('时间范围变化:', dates, dateStrings);
  }

  /**
   * 查询
   */
  function handleSearch() {
    const searchParams: any = {};
    if (timeRange.value && timeRange.value.length === 2) {
      searchParams.startTime = timeRange.value[0]?.format ? timeRange.value[0].format('YYYY-MM-DD HH:mm:ss') : timeRange.value[0];
      searchParams.endTime = timeRange.value[1]?.format ? timeRange.value[1].format('YYYY-MM-DD HH:mm:ss') : timeRange.value[1];
    }
    setProps({ searchInfo: { ...searchParams, houseId: rowId.value } });
    reload();
  }

  /**
   * 重置
   */
  function handleReset() {
    timeRange.value = [];
    setProps({ searchInfo: { houseId: rowId.value } });
    reload();
  }

  /**
   * 处理图片URL
   */
  function getImageUrls(text: string) {
    if (!text) return [];
    return typeof text === 'string' ? text.split(',').map(url => url.trim()).filter(url => url) : [text];
  }

  //  const { adaptiveWidth } = useDrawerAdaptiveWidth();
</script>
